var baseUrl = 'http://sxsw.grooveshark.com/';
var currentSongID = null;
var currentSongStatus = '';
var tweets = null;
var tweetIndex = 0;
var showTweetStream = false;
var hashtag = getParameterByName('hashtag');
if (!hashtag) hashtag = 'sxsw';
var playlistID = getParameterByName('playlist');

function timeAgo(dateString) {
  var rightNow = new Date();
  var then = new Date(dateString);
  if ($.browser.msie) {
    // IE can't parse these crazy Ruby dates
    then = Date.parse(dateString.replace(/( \+)/, ' UTC$1'));
  }
  var diff = rightNow - then;
  var second = 1000,
      minute = second * 60,
      hour = minute * 60,
      day = hour * 24,
      week = day * 7;
  if (isNaN(diff) || diff < 0) {
    return ""; // return blank string if unknown
  }
  if (diff < second * 2) {
    // within 2 seconds
    return "right now";
  }
  if (diff < minute) {
    return Math.floor(diff / second) + " seconds ago";
  }
  if (diff < minute * 2) {
    return "about 1 minute ago";
  }
  if (diff < hour) {
    return Math.floor(diff / minute) + " minutes ago";
  }
  if (diff < hour * 2) {
    return "about 1 hour ago";
  }
  if (diff < day) {
    return  Math.floor(diff / hour) + " hours ago";
  }
  if (diff > day && diff < day * 2) {
    return "yesterday";
  }
  if (diff < day * 365) {
    return Math.floor(diff / day) + " days ago";
  }
  else {
    return "over a year ago";
  }
};

function getParameterByName(name) {
  var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
  return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}

function embedPlayer() {
  var vars = {
    hostname: "cowbell.grooveshark.com",
  };
  var params = { scale:'noScale', salign:'lt', menu:'false', allowScriptAccess: 'always', wmode: 'window' };
  var attributes = { id:'jsPlayer', name:'jsPlayer' };
  var swfwrapper = 'swfwrapper';
  if (!document.getElementById('swfwrapper')) {
    $(document.body).append('<div id="swfwrapper"></div>');
  }
  swfobject.embedSWF("http://listen.grooveshark.com/JSPlayer.swf", "swfwrapper",
                     "1", "1", "9.0.0", "http://listen.grooveshark.com/expressInstall.swf",
                     vars, params, attributes, onEmbed);
}

function onPlayerStatus(status) {
  currentSongStatus = status;
}

function onSongComplete() {
  $.getJSON(baseUrl + 'update.php?callback=?&action=advance', handleStatus);
}

function onSongPosition(data) {
  if (data.position && (data.duration > 0) && (data.position > 3500)) {
    $('#positionbar').animate(
      { width: Math.round(3 + 97 * data.position / data.duration) + '%' },
      { duration: 400, queue: false });
  } else {
    $('#positionbar').animate(
      { width: '3%' },
      { duration: 400, queue: false });
  }
}

function setCallbacks() {
  if (window.player && window.player.setStatusCallback) {
    window.player.setStatusCallback('onPlayerStatus');
    window.player.setSongCompleteCallback('onSongComplete');
    window.player.setPositionCallback('onSongPosition');
  } else {
    setTimeout(setCallbacks, 1000);
  }
}

function onEmbed(e) {
  if (e.success) {
    window.player = e.ref;
    setTimeout(setCallbacks, 1000);
  }
}

function handleStatus(data) {
  if ((data.length == 0) || !data.NowPlaying) {
    return;
  }
  if (window.player && window.player.playSong && (currentSongID != data.NowPlaying.SongID)) {
    currentSongID = data.NowPlaying.SongID;
    window.player.stopStream();
    window.player.playSong(currentSongID);
    window.player.setVolume(100);
    $('#positionbar').css('width', '3%');
    $('#nowplayingartist').html(data.NowPlaying.ArtistName);
    $('#nowplayingtitle').html(data.NowPlaying.SongName);
    $('#tinysong').html(data.NowPlaying.TinysongURL.replace('http://',''));
    $('#tinysong').attr('href', data.NowPlaying.TinysongURL);
    $('#song1artist').html(data.Song1.ArtistName);
    $('#song1title').html(data.Song1.SongName);
    $('#song2artist').html(data.Song2.ArtistName);
    $('#song2title').html(data.Song2.SongName);
    $('#song3artist').html(data.Song3.ArtistName);
    $('#song3title').html(data.Song3.SongName);
    $(".title, .artist").shorten({ width: 540 });
    if (data.NowPlaying.ImageURL && data.Song1.ImageURL && data.Song2.ImageURL && data.Song3.ImageURL) {
      $.loadImages([data.NowPlaying.ImageURL, data.Song1.ImageURL, data.Song3.ImageURL, data.Song3.ImageURL], function() {
        $('#nowplayingimg').attr('src', data.NowPlaying.ImageURL);
        $('#song1img').attr('src', data.Song1.ImageURL);
        $('#song2img').attr('src', data.Song2.ImageURL);
        $('#song3img').attr('src', data.Song3.ImageURL);
      });  
    }
  }
  var maxvotes = Math.max(10, data.Song1.Votes, data.Song2.Votes, data.Song3.Votes);
  $('#song1votes .votebar').css('width', Math.round(100*data.Song1.Votes/maxvotes) + '%');
  $('#song2votes .votebar').css('width', Math.round(100*data.Song2.Votes/maxvotes) + '%');
  $('#song3votes .votebar').css('width', Math.round(100*data.Song3.Votes/maxvotes) + '%');
}

function handleTweets(data) {
  if (data.length == 0) {
    return;
  }
  tweets = data.results;
}

function updateStatus() {
  $.getJSON(baseUrl + 'status.php?callback=?&action=status', handleStatus);
  window.setTimeout(updateStatus, 2000);
}

function updatePlaylist() {
  $.getJSON(baseUrl + 'update.php?callback=?&action=replace_songs&playlist=' + playlistID, handleStatus);
  window.setTimeout(updateStatus, 2000);
}

function updateTweets() {
  $.getJSON('http://search.twitter.com/search.json?callback=?&result_type=mixed&q=%23' + hashtag, handleTweets);
  window.setTimeout(updateTweets, 60000);
}

function showNextTweet() {
  if (tweets && (tweets.length > 0)) {
    $('#tweet').animate({right: '-=500'}, function() {
      var tweet = tweets[tweetIndex];
      tweetIndex = (tweetIndex + 1) % tweets.length;
      $('#username').html('@' + tweet.from_user);
      $('#tweet time').html(timeAgo(tweet.created_at));
      $('#tweettext p').html(tweet.text);
      $('#tweet').show();
      $('#tweet').animate({right: '+=500'});
    });
  }
  return false;
}

function resizeFrame() { 
  var size = $('#voting').offset().top - $('#nowplaying').offset().top;
  $('#nowplaying').css('height', size + 'px');
  $('#albumart').css('height', size + 'px');
  $('#albumart').css('width', size + 'px');
  $('#nowplayingmeta').css('height', size + 'px');
  $('#nowplayingimg').css('height', (size * 0.8) + 'px');
  $('#nowplayingimg').css('width', (size * 0.8) + 'px');
  $('#nowplayingimg').css('top', (0.5 * (size - $('#nowplayingimg').height())) + 'px');
  $('#nowplayingmeta').css('top', (.6 * (size - $('#nowplayingimg').height())) + 'px');
}

$(document).ready(function() {
  $('#tweet').hide();
  $('#hashtag').html('<a target="_blank" href="http://search.twitter.com/search?q=%23' + hashtag + '">#' + hashtag + '</a>');
  embedPlayer();
  if (playlistID) {
    updatePlaylist();
  } else {
    updateStatus();
  }
  if (showTweetStream) {
    updateTweets();
    window.setInterval(showNextTweet, 10000);
  }
  $.backstretch("images/body-bg.jpg", {speed: 500});
  resizeFrame();
  $.event.add(window, "resize", resizeFrame);
});


/*
 * jQuery Backstretch
 * Version 1.1.2
 * http://srobbin.com/jquery-plugins/jquery-backstretch/
 *
 * Add a dynamically-resized background image to the page
 *
 * Copyright (c) 2010 Scott Robbin (srobbin.com)
 * Dual licensed under the MIT and GPL licenses.
*/
(function(a){a.backstretch=function(k,i,l){function m(c){try{f={left:0,top:0};d=e.width();b=d/j;if(b>=e.height()){g=(b-e.height())/2;h.centeredY&&a.extend(f,{top:"-"+g+"px"})}else{b=e.height();d=b*j;g=(d-e.width())/2;h.centeredX&&a.extend(f,{left:"-"+g+"px"})}a("#backstretch img").width(d).height(b).css(f)}catch(n){}typeof c=="function"&&c()}var h={centeredX:true,centeredY:true,speed:0},e="onorientationchange"in window?a(document):a(window),j,d,b,g,f;i&&typeof i=="object"&&a.extend(h,i);a(document).ready(function(){if(k){var c= a("<div />").attr("id","backstretch").css({left:0,top:0,position:"fixed",overflow:"hidden",zIndex:-9999}),n=a("<img />").css({position:"relative",display:"none"}).bind("load",function(o){var p=a(this);j=a(o.target).width()/a(o.target).height();m(function(){p.fadeIn(h.speed,function(){typeof l=="function"&&l()})})}).appendTo(c);a("body").prepend(c);n.attr("src",k);a(window).resize(m)}});return this}})(jQuery);

/*
 * Shorten, a jQuery plugin to automatically shorten text to fit in a block or a pre-set width and configure how the text ends.
 * Copyright (C) 2009-2011  Marc Diethelm
 * License: (GPL 3, http://www.gnu.org/licenses/gpl-3.0.txt) see license.txt
 */

(function(a){function s(g,c){return c.measureText(g).width}function t(g,c){c.text(g);return c.width()}var q=false,o,j,k;a.fn.shorten=function(){var g={},c=arguments,r=c.callee;if(c.length)if(c[0].constructor==Object)g=c[0];else if(c[0]=="options")return a(this).eq(0).data("shorten-options");else g={width:parseInt(c[0]),tail:c[1]};this.css("visibility","hidden");var h=a.extend({},r.defaults,g);return this.each(function(){var e=a(this),d=e.text(),p=d.length,i,f=a("<span/>").html(h.tail).text(),l={shortened:false, textOverflow:false};i=e.css("float")!="none"?h.width||e.width():h.width||e.parent().width();if(i<0)return true;e.data("shorten-options",h);this.style.display="block";this.style.whiteSpace="nowrap";if(o){var b=a(this),n=document.createElement("canvas");ctx=n.getContext("2d");b.html(n);ctx.font=b.css("font-style")+" "+b.css("font-variant")+" "+b.css("font-weight")+" "+Math.ceil(parseFloat(b.css("font-size")))+"px "+b.css("font-family");j=ctx;k=s}else{b=a('<table style="padding:0; margin:0; border:none; font:inherit;width:auto;zoom:1;position:absolute;"><tr style="padding:0; margin:0; border:none; font:inherit;"><td style="padding:0; margin:0; border:none; font:inherit;white-space:nowrap;"></td></tr></table>'); $td=a("td",b);a(this).html(b);j=$td;k=t}b=k.call(this,d,j);if(b<i){e.text(d);this.style.visibility="visible";e.data("shorten-info",l);return true}h.tooltip&&this.setAttribute("title",d);if(r._native&&!g.width){n=a("<span>"+h.tail+"</span>").text();if(n.length==1&&n.charCodeAt(0)==8230){e.text(d);this.style.overflow="hidden";this.style[r._native]="ellipsis";this.style.visibility="visible";l.shortened=true;l.textOverflow="ellipsis";e.data("shorten-info",l);return true}}f=k.call(this,f,j);i-=f;f=i*1.15; if(b-f>0){f=d.substring(0,Math.ceil(p*(f/b)));if(k.call(this,f,j)>i){d=f;p=d.length}}do{p--;d=d.substring(0,p)}while(k.call(this,d,j)>=i);e.html(a.trim(a("<span/>").text(d).html())+h.tail);this.style.visibility="visible";l.shortened=true;e.data("shorten-info",l);return true})};var m=document.documentElement.style;if("textOverflow"in m)q="textOverflow";else if("OTextOverflow"in m)q="OTextOverflow";if(typeof Modernizr!="undefined"&&Modernizr.canvastext)o=Modernizr.canvastext;else{m=document.createElement("canvas"); o=!!(m.getContext&&m.getContext("2d")&&typeof m.getContext("2d").fillText==="function")}a.fn.shorten._is_canvasTextSupported=o;a.fn.shorten._native=q;a.fn.shorten.defaults={tail:"&hellip;",tooltip:true}})(jQuery);


/*
 * jQuery Image Preloader with Callback Mechanism
 * Version 1.0.1
 * http://plugins.jquery.com/project/Image-Preloader
*/
(function(c){var h=[];c.loadImages=function(a,d){a instanceof Array||(a=[a]);for(var e=a.length,f=0,g=e;g--;){var b=document.createElement("img");b.onload=function(){f++;f>=e&&c.isFunction(d)&&d()};b.src=a[g];h.push(b)}}})(jQuery);
